package com.linln.admin.pcs.controller;


import com.linln.admin.pcs.service.NotificationMiddleService;
import com.linln.admin.pcs.service.VerifyLogService;
import com.linln.admin.system.service.AppService;
import com.linln.common.data.QuerySpec;
import com.linln.common.utils.HelperUtil;
import com.linln.common.utils.HttpServletUtil;
import com.linln.common.utils.ResultVoUtil;
import com.linln.common.utils.ValidationUtil;
import com.linln.component.actionLog.annotation.EntityParam;
import com.linln.component.shiro.ShiroUtil;
import com.linln.modules.system.domain.*;
import com.linln.modules.system.repository.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.StringWriter;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 服务项目管理
 */
@Controller
@RequestMapping("/pcs/project")
public class ProjectController {

    @Autowired
    private AppService appService;
    @Autowired
    private  ProjectRepository projectRepository;
    @Autowired
    private VerifyLogService verifyLogService;
    @Autowired
    private ThymeleafViewResolver thymeleafViewResolver;
    @Autowired
    private ContractTplRepository contractTplRepository;
    @Autowired
    private  ProjectStageRepository projectStageRepository;
    @Autowired
    private CompanyRepository companyRepository;
    @Autowired
    private NotificationMiddleService notificationMiddleService;
    @Autowired
    private UserRepository  userRepository;


    /**
     * 专业陪护项目列表页面
     */
    @GetMapping("/index")
    @RequiresPermissions("pcs:project:index")
    public ResponseEntity<?> index(Model model, @EntityParam Project project) {
        return appService.layTable(projectRepository, before -> {
                   model.addAttribute("verifyStatus", HttpServletUtil.getParameter("verifyStatus",""));
                    // 添加模板变量
                    return model;

                },

                after -> {
                    QuerySpec querySpec = QuerySpec.matching();
                    querySpec.withMatcher("title", QuerySpec.LIKE)
                            .withMatcherValue("type", QuerySpec.EQUAL,"1")
                            .withMatcher("verifyStatus", QuerySpec.EQUAL);
                    User user = ShiroUtil.getSubject();
                    if (user.getType()!=null&&user.getType().equals("2")) {
                        Long companyId = user.getCompanyId();
                        querySpec.withMatcherValue("companyId", QuerySpec.EQUAL,companyId.toString());
                    }
                    return QuerySpec.of(querySpec);
                },

                "/pcs/project/index",

                (pageResult) -> {
                    // 在这里处理 pageResult
                    pageResult.getContent().forEach(item -> {
                        Project v = (Project) item;
                        Company company = companyRepository.getById(v.getCompanyId());
                        if(company!=null){
                            v.setCompanyName(company.getName());
                        }
                    });
                }

        );

    }


    /**
     * 表单
     */
    @RequestMapping("/form")
    @RequiresPermissions("pcs:project:add")
    public ResponseEntity<?> form(Model model, @EntityParam Project project) throws Exception {

        return appService.form(projectRepository, "/pcs/project/form",
                (isEdit) -> {
                    QuerySpec querySpec = QuerySpec.matching();
                    querySpec.withMatcherValue("companyId", QuerySpec.EQUAL, ShiroUtil.getSubject().getCompanyId().toString())
                            .withMatcherValue("verifyStatus", QuerySpec.EQUAL, "1");
                    List<ContractTpl> contractTplList = contractTplRepository.findAll(QuerySpec.of(querySpec));
                    model.addAttribute("contractTplList", contractTplList);

                    return model;

                },
                (isEdit, vo) -> {

                    model.addAttribute("vo", vo);
                    Project v = (Project) vo;
                    QuerySpec querySpec2 = QuerySpec.matching();
                    querySpec2.withMatcherValue("projectId", QuerySpec.EQUAL, v.getId().toString());
                    List<ProjectStage> projectStageList = projectStageRepository.findAll(QuerySpec.of(querySpec2));
                    model.addAttribute("projectStageList", projectStageList);
                    // 你可以在这里添加其他逻辑
                    return model;
                },
                (data) -> {
                    // 保存前数据校验
                    List<ValidationUtil.ValidationRule<?>> rules = new ArrayList<>();
                    // 添加邮箱的校验规则
                    //            rules.add(new ValidationUtil.ValidationRule<>(
                    //                    porter.getCardNo(),
                    //                    email -> email != null ,
                    //                    "Email格式不正确"
                    //            ));

                    // 执行校验
                    return ValidationUtil.validateFields(rules);

                },
                (data) -> {

                    // 数据处理
                    if(project.getId() != null){
                        Project origin = projectRepository.getById(project.getId());
                        project.setStatus(origin.getStatus());
                        project.setCompanyId(origin.getCompanyId());
                        project.setCreateUser(origin.getCreateUser());
                        project.setCreateTime(origin.getCreateTime());
                    }else{
                        User user = ShiroUtil.getSubject();
                        project.setCompanyId(user.getCompanyId());
                        project.setCompanyName(user.getCompanyName());
                    }
                    Company company = companyRepository.findById(project.getCompanyId()).get();
                    project.setIsWl(company.getIsWl());

                    project.setStatus((byte) 1);
                    project.setVerifyStatus(0);
                    return project;
                },

                (data) -> {
                    // 保存后续逻辑在这写
                });

    }


    @PostMapping("/save")
    @RequiresPermissions("pcs:project:add")
    public ResponseEntity<?> save(Project project, HttpServletRequest request) throws Exception {
        // 解码 content
        if (project.getContent() != null) {
            project.setContent(URLDecoder.decode(project.getContent(), "UTF-8"));
        }
        // 数据处理
        if(project.getId() != null){
            Project origin = projectRepository.getById(project.getId());
            project.setStatus(origin.getStatus());
            project.setCompanyId(origin.getCompanyId());
            project.setCreateUser(origin.getCreateUser());
            project.setCreateTime(origin.getCreateTime());
        }else{
            User user = ShiroUtil.getSubject();
            project.setCompanyId(user.getCompanyId());
            project.setCompanyName(user.getCompanyName());
        }
        if( project.getIsNeedSignContract()==1){
            if(project.getContractTplId()==null || project.getContractTplId()==0 ){
                return ResponseEntity.ok(ResultVoUtil.error("请选择合同模板"));
            }
        }

        project.setStatus((byte) 1);
        project.setVerifyStatus(0);
        Company company = companyRepository.findById(project.getCompanyId()).get();
        project.setIsWl(company.getIsWl());
        Project saveOrgin = projectRepository.save(project);
        List<ProjectStage> projectStageList = project.getProjectStageList();
        //分割删除的阶段
        String[] removeStageId = project.getRemoveStageId().split(",");
        if(!project.getRemoveStageId().equals("")){
            for (int i = 0; i < removeStageId.length; i++) {
                ProjectStage removeStage = projectStageRepository.getById(Long.parseLong(removeStageId[i]));
                removeStage.setStatus((byte) 3);
                projectStageRepository.save(removeStage);
            }

        }
        projectStageList.forEach(projectStage -> {
            if(projectStage.getTitle()!=null){
                projectStage.setProjectId(saveOrgin.getId());
                projectStage.setCompanyId(saveOrgin.getCompanyId());
                projectStage.setStatus((byte) 1);
                projectStageRepository.save(projectStage);
            }

        });

        //推送数据到中台
        String content = "您有一个专业陪护项目【"+project.getTitle()+"】需要审核，请及时处理";
        QuerySpec querySpecUser = QuerySpec.matching();
        querySpecUser.withMatcherValue("type", QuerySpec.EQUAL, "0");
        List<User> userList = userRepository.findAll(QuerySpec.of(querySpecUser));
        userList.forEach(user -> {
            notificationMiddleService.send(content,  "/pcs/project/index?verifyStatus=0", user.getMiddleUserId(), request);
        });
      //  notificationMiddleService.send(content,  "/pcs/project/index?verifyStatus=0", saveOrgin.getId(), request);


        return ResponseEntity.ok(ResultVoUtil.success("成功"));
    }


    @RequestMapping("/detail")
    public String detail(@RequestParam Long id, Model model) throws Exception{
        Project projectOrgin = projectRepository.getById(id);
        model.addAttribute("vo",projectOrgin);
        QuerySpec querySpec = QuerySpec.matching();
        querySpec.withMatcherValue("projectId", QuerySpec.EQUAL, String.valueOf(id));
        List<ProjectStage> projectStageList = projectStageRepository.findAll(QuerySpec.of(querySpec));
        model.addAttribute("projectStageList",projectStageList);
        QuerySpec querySpec1 = QuerySpec.matching();
        querySpec1.withMatcherValue("companyId", QuerySpec.EQUAL, ShiroUtil.getSubject().getCompanyId().toString());
        List<ContractTpl> contractTplList = contractTplRepository.findAll(QuerySpec.of(querySpec1));
        model.addAttribute("contractTplList", contractTplList);
        return "/pcs/project/detail";
    }



    /**
     * 修改状态
     * @param model
     * @param project
     * @return
     * @throws Exception
     */
    @RequestMapping("/state")
    @RequiresPermissions("pcs:project:state")
    public ResponseEntity<?> state(Model model, @EntityParam Project project) throws Exception {

        return appService.save(projectRepository, (data) -> {

            // 校验数据
            return ValidationUtil.validateFields(new ArrayList<>());

        }, (data) -> {
            // 处理数据
            Project origin = projectRepository.getById(project.getId());
            origin.setStatus(project.getStatus());

            return origin;

        }, (data) -> {
            // 更新后操作
        });

    }


    /**
     * 项目审核
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping("/verify")
    @RequiresPermissions("pcs:project:verify")
    public ResponseEntity<?> verify(Model model) throws Exception {

        String ids = HttpServletUtil.getParameter("ids");
        Integer verifyStatus = HttpServletUtil.getParameterInt("verifyStatus");
        List<Long> idList = Arrays.stream(ids.split(","))
                .map(String::trim)
                .map(Long::parseLong)
                .collect(Collectors.toList());
        idList.forEach(item -> {
            Project project = projectRepository.getById(item);
            project.setVerifyStatus(verifyStatus);
            verifyLogService.setVerifyLog(item, verifyStatus,3,"");
            projectRepository.save(project);
        });
        return ResponseEntity.ok(ResultVoUtil.success("成功"));

    }


    //权限审核
    @RequestMapping("/canal")
    @RequiresPermissions("pcs:project:verify")
    public ResponseEntity<?> canal(Model model, @EntityParam Project project) {
        String method = HttpServletUtil.getMethod();
        if (method.equals("GET")) {
            String id = HttpServletUtil.getParameter("id");
            Integer verifyStatus = HttpServletUtil.getParameterInt("verifyStatus");
            model.addAttribute("id", id);
            model.addAttribute("verifyStatus", verifyStatus);
            // 必须手动渲染模板
            Context context = new Context();
            // 将数据加入到 Thymeleaf 上下文中
            context.setVariables(model.asMap());
            // 使用 Thymeleaf 渲染模板
            StringWriter writer = new StringWriter();
            thymeleafViewResolver.getTemplateEngine().process("/pcs/project/verify", context, writer);

            return ResponseEntity.ok( writer.toString());
        }else{
            Project project1 = projectRepository.getById(project.getId());
            String remark = "";

            if(project.getRemark()!=null){
                //驳回权限申请
                remark = project.getRemark();
                project1.setRemark(project.getRemark());
            }

            project1.setVerifyStatus(project.getVerifyStatus());
            verifyLogService.setVerifyLog(project.getId(), project.getVerifyStatus(),1,remark);
            projectRepository.save(project1);
            return ResponseEntity.ok(ResultVoUtil.success("成功"));
        }

    }







}
